package net.watchnow.dao;

import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import cn.hutool.core.util.StrUtil;
import net.watchnow.bean.TestBean;

@Component
public class TestBeanDao {
	@Autowired
    private MongoTemplate mongoTemplate;
	
	public void saveOne (TestBean bean) {
		mongoTemplate.save(bean);
	}
	
	
	public void updateOne (TestBean bean) {
		if (bean != null && StrUtil.isNotEmpty(bean.getId())) {
			Query query=new Query(Criteria.where("id").is(bean.getId()));
	        Update update= new Update().set("userName", bean.getUserName()).set("passWord", bean.getPassWord()).set("num", bean.getNum())
	        		.set("time", bean.getTime());
	        //更新查询返回结果集的第一条
	        mongoTemplate.updateFirst(query,update,TestBean.class);
		}
	}
	
	public TestBean findOne (String idOrName) {
		Query query=new Query(Criteria.where("userName").is(idOrName));
		TestBean bean = mongoTemplate.findOne(query , TestBean.class);
		if (bean == null) {
			Query query2=new Query(Criteria.where("id").is(idOrName));
			bean = mongoTemplate.findOne(query2 , TestBean.class);
		}
		return bean;
	}
	
	public void deleteOne (String id) {
		Query query=new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query,TestBean.class);
	}
	public void deleteOneByName (String name) {
		Query query=new Query(Criteria.where("userName").is(name));
		mongoTemplate.remove(query,TestBean.class);
	}
}
